package com.flying.server.network.handler;


import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;

import com.flying.server.network.msg.MsgType;
import com.flying.server.network.msg.ORMsg;
import com.flying.server.network.msg.OWMsg;
import com.flying.server.protocol.SessionManager;
import com.flying.server.protocol.UserSession;
import com.flying.server.protocol.proto.OuyuProto.MessageStatus;
import com.flying.server.protocol.proto.OuyuProto.Session;

public class InitMsgHandler implements IMsgHandler{

	@Override
	public void onMsg(ORMsg rMsg) {
		
		UserSession session = SessionManager.getInstance().createSession(rMsg.getChannel());
		
		OWMsg wMsg = null;
		if (session == null)
		{
			wMsg = createFailedMsg(rMsg.getMsgSeq());
		}
		else
		{
			wMsg = createSessionMsg(rMsg.getMsgSeq(),session);
		}
		rMsg.getChannel().write(wMsg);
	}
	
	private OWMsg createSessionMsg(short msgSeq,UserSession session)
	{
		Session s = Session.newBuilder().setSessionKey(session.getSessionID()).build();
		System.out.println("sessionkey="+s.getSessionKey());
		MessageStatus status = MessageStatus.newBuilder().setMessageStatus(MessageStatus.Status.SUCCESSED).build();
		byte[] statusBytes = status.toByteArray();
		byte[] sessionBytes = s.toByteArray();
		ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(512);
		
		channelBuffer.writeInt(statusBytes.length);
		channelBuffer.writeBytes(statusBytes);
		
		channelBuffer.writeInt(sessionBytes.length);
		channelBuffer.writeBytes(sessionBytes);
		OWMsg msg = new OWMsg(MsgType.INIT,msgSeq,channelBuffer);
		
		return msg;
	}
	
	private OWMsg createFailedMsg(short msgSeq)
	{
		MessageStatus status = MessageStatus.newBuilder().setMessageStatus(MessageStatus.Status.SUCCESSED).build();
		byte[] statusBytes = status.toByteArray();
		ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(10);
		
		channelBuffer.writeInt(statusBytes.length);
		channelBuffer.writeBytes(status.toByteArray());
		
		OWMsg msg = new OWMsg(MsgType.INIT,msgSeq,channelBuffer);
		
		return msg;
	}
}
